package com.dgwcode.subclass;

import java.util.List;

import org.hibernate.Session;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import utils.HibernateUtils;

public class HibernateTest {
	
	private Session session;

	@Before
	public void before() {
		session = HibernateUtils.getSession();
		session.beginTransaction();
	}
	/**
	 * 缺点:
	 * 1. 使用了辨别者列.
	 * 2. 子类独有的字段不能添加非空约束.
	 * 3. 若继承层次较深, 则数据表的字段也会较多. 
	 */
	/**
	 * 查询:
	 * 1. 查询父类记录, 只需要查询一张数据表
	 * 2. 对于子类记录, 也只需要查询一张数据表
	 */
	@Test
	public void testGET() {
		Person person = session.get(Person.class, 1);
		
		System.out.println(person.getName());
		
		//具有序号的情况下，hibernate自动维护属性列
		Worker worker = session.get(Worker.class, 3);
		
		System.out.println(worker.getCompany());
		
		//默认
		List list = session.createQuery("FROM Person").list();
		
		//自动加上类型
		List list2 = session.createQuery("FROM Student").list();
		System.out.println(list.size());
		System.out.println(list2.size());
		
	}
	
	/**
	 *  1.subclass 只产生一张表；
	 *  2.辨别者列是hibernate自动维护的
	 */
	@Test
	public void testSubClass() {
		Person person = new Person();
		
		person.setName("DGW");
		person.setAge(25);
		
		Student student = new Student();
		student.setName("DGW");
		student.setAge(25);
		student.setSchool("WSY");
		
		session.save(person);
		
		//如果不写子类属性，并不会自动映射父类属性
		/*session.save(person);
		session.save(student);*/
		session.save(student);
		
		Worker worker = new Worker();
		worker.setName("DGW");
		worker.setAge(25);
		worker.setCompany("baidu");
		
		session.save(worker);
	}
	
	@After
	public void after() {
		session.getTransaction().commit();
		session.close();
	}

}
